package com.example.administrator.nurse.fragment;

import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.administrator.nurse.R;
import com.example.administrator.nurse.base.BaseFragment;
import com.example.administrator.nurse.common;
import com.example.administrator.nurse.model.CommonViewHolder;
import com.example.administrator.nurse.model.RecyclerViewCommonAdapter;
import com.example.administrator.nurse.model.bean.FeatureActivityBean;
import com.example.administrator.nurse.present.DataPicActivity;
import com.example.administrator.nurse.util.recyclerViewHelper;
import com.example.administrator.nurse.widget.LoginInputEdit;
import com.example.administrator.nurse.widget.SearchInput;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/7.
 *
 */

public class FeatureDataFragment extends BaseFragment {

    private List<FeatureActivityBean> list = new ArrayList<>();
    private RecyclerViewCommonAdapter adapter;
    private recyclerViewHelper recyclerViewHelper;
    private SearchInput SearchInput;
    private LinearLayout container;
    private View selectTemp;
    private int selectIndex=0;


    private void onItemSelectListener(final View... view){ /** 个数动态变化 */
        for(final View viewT : view){
            viewT.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(selectTemp!=null){
                        /** 处理上一个被选中的 */
                        ((TextView)selectTemp.findViewById(R.id.text)).setTextColor(Color.GRAY);
                        selectTemp.findViewById(R.id.line).setVisibility(View.GONE);
                    }
                    selectTemp = viewT;
                    ((TextView)viewT.findViewById(R.id.text)).setTextColor(getResources().getColor(R.color.navbar)); /** 显示颜色 */
                    viewT.findViewById(R.id.line).setVisibility(View.VISIBLE); /** 显示出颜色 */
                    /** 下面标记 */
                    selectIndex = (Integer)viewT.getTag();
                }
            });
        }
    }
    @Override
    protected void initView(View rootView) {
        container= (LinearLayout) f(R.id.container);
        View room= LayoutInflater.from(activity).inflate(R.layout.select_item,(ViewGroup)activity.getWindow().getDecorView(),false);
        container.addView(room);
        selectTemp=room;

        View patient= LayoutInflater.from(activity).inflate(R.layout.select_item, (ViewGroup) activity.getWindow().getDecorView(), false);
        container.addView(patient);

        View recode= LayoutInflater.from(activity).inflate(R.layout.select_item, (ViewGroup) activity.getWindow().getDecorView(), false);
        container.addView(recode);

        initAdapter();
        onItemSelectListener(room, patient, recode);
        recyclerViewHelper=new recyclerViewHelper(activity,(XRecyclerView) f(R.id.recyclerView))
                .withAdapter(adapter)
                .withLayoutManager(null)
                .withPullRefrshOpen(true)
                .withRefresh(new recyclerViewHelper.refreshListener() {
                    @Override
                    public void refresh() {
                        getData(false,null);
                    }
                })
                .withLoadMore(new recyclerViewHelper.loadMoreListener() {
                    @Override
                    public void loadMore() {
                        getData(true,null);
                    }
                })
                .initRecyclerView();

        //recyclerViewHelper.addItemDecoration(DivierItemDecoration.VERTICAL_LIST);

        SearchInput = new SearchInput(getActivity(),f(R.id.search_common))
                .withTypeMenu(R.menu.body_data_type)
                .withSortMenu(R.menu.sort)
                .withMenuItemClickListener(new SearchInput.OnMenuItemClickListener() {
                    @Override
                    public void menuTypeItemClick(MenuItem item) { // 类型下拉点击
                        switch (item.getItemId()) {
                            case R.id.first :typeSelect = 0 ;break;
                            case R.id.second:typeSelect = 1 ;break;
                            case R.id.third :typeSelect = 2 ;break;
                            case R.id.fourth:typeSelect = 3 ;break;
                            case R.id.five  :typeSelect = 4 ;break;
                            case R.id.six   :typeSelect = 5 ;break;
                            case R.id.seven :typeSelect = 6 ;break;
                            case R.id.eight :typeSelect = 7 ;break;
                            case R.id.nine  :typeSelect = 8 ;break;
                            case R.id.ten   :typeSelect = 9 ;break;
                            case R.id.eleven:typeSelect = -1;break;
                        }
                        getData(false,null);
                    }

                    @Override
                    public void menuSortItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.first:
                                sortSelect = 0;
                                break;
                            case R.id.second:
                                sortSelect = 1;
                                break;
                        }
                        getData(false,null);
                    }
                })
                .withSearchClickListener(new SearchInput.OnSearchClickListener() {
                    @Override
                    public void searchClick(LoginInputEdit searchInput) {
                        if (searchInput.isOk("搜索关键字不能少于1个")) {
                            getData(false, searchInput.getStringText());
                        }
                    }
                })
                .init();

        /** 第一次加载数据 */
        getData(false,null);
    }

    private final int GetDataNormal = 0x11;
    private final int GetDataMore   = 0x12;
    private int typeSelect=-1,sortSelect=0,lid;
    private void getData(boolean loadMore,String isSearch){
        startLoadingDialog();
        RequestParams requestParams = new RequestParams();
        requestParams.put("id", common.nId);
        requestParams.put("sort", sortSelect);
        if(isSearch!=null){
            requestParams.put("con",isSearch);
        }else{
            SearchInput.searchInput.setText("");
        }
        List<String> l = new ArrayList<>();
        switch (typeSelect){
            case -1: l.add("全部"  )  ;break;
            case  0: l.add("体温")    ;break;
            case  1: l.add("舒张压") ;break;
            case  2: l.add("收缩压") ;break;
            case  3: l.add("血糖餐前") ;break;
            case  4: l.add("血糖餐后") ;break;
            case  5: l.add("脉搏") ;break;
            case  6: l.add("血氧") ;break;
            case  7: l.add("尿量") ;break;
            case  8: l.add("呼吸") ;break;
            case  9: l.add("大便") ;break;
        }
        if(sortSelect==0){
            l.add("时间升序");
        }else{
            l.add("时间降序");
        }
        if(typeSelect!=-1){
            requestParams.put("type",typeSelect);
        }
        if(loadMore){
            requestParams.put("lid",lid); /** 加载更多的 id */
            doPost(GetDataMore, l, common.Host + "/Controller/healthController.php?func=getHealthData", requestParams);
        }else {
            doPost(GetDataNormal, l, common.Host + "/Controller/healthController.php?func=getHealthData", requestParams);
        }
    }

    @Override
    public int setLayoutId() {
        return R.layout.feature_data_layout;
    }

    @Override
    protected void onFailure(int requestCode, Object object, String errorMsg) {
        stopLoadingDialog();
    }

    @Override
    protected void onSuccess(int requestCode, Object object, String response) {
        stopLoadingDialog();
        List<String> l = (List<String>) object;
        switch (requestCode){
            case GetDataNormal:
                recyclerViewHelper.getRecyclerView().refreshComplete();
                if(response.trim().equals("0")){
                    t("暂无"+l.get(0)+"记录!");
                    list.clear();
                    adapter.notifyDataSetChanged();
                    //userTestData(); /** 数据库没数据，使用测试数据，日后可以删除 */
                }else {
                    t(response);
                    Log.d("zzzzz", l.get(0));
                    SearchInput.type.setText(l.get(0));
                    SearchInput.sort.setText(l.get(1));
                    dealDataJson(response, false);
                }
                break;
            case GetDataMore:
                recyclerViewHelper.getRecyclerView().loadMoreComplete();
                SearchInput.type.setText(l.get(0));
                SearchInput.sort.setText(l.get(1));
                dealDataJson(response, true);
                break;
        }
    }

    private void dealDataJson(String response,boolean isLoadMore){
        if(response!=null){
            try{
                JSONArray jsonArray = new JSONArray(response);
                int length = jsonArray.length();
                if(length>0 && !isLoadMore){
                    list.clear();
                }
//        for (int i=0;i<20;i++){
//            FeatureActivityBean bean=new FeatureActivityBean();
//            bean.setPatientInfo("王小二，女，68岁");
//            bean.setDoctor("黄华佗");
//            bean.setMeasureTime("2016-3-15 12:13:12");
//            bean.setType("体温");
//            bean.setType1("°C");
//            list.add(bean);
//        }
                for(int i=0;i<length;i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    FeatureActivityBean bean = new FeatureActivityBean();

                    bean.setPatientInfo(
                            getJSONValue(jsonObject, "name") + "," +
                                    (getJSONValue(jsonObject, "sex").trim().equals("1") ? "男" : "女") + "," +
                                    getJSONValue(jsonObject, "age") + "岁" + ","
                    );
                    bean.setDoctor(getJSONValue(jsonObject, "doctor"));
                    bean.setMeasureTime(getJSONValue(jsonObject, "entryTime"));

                    int type = getJSONINTValue(jsonObject, "type");
                    switch (type){
                        case 0:
                            bean.setType("体温"); bean.setType1("°C");bean.setContent(getJSONValue(jsonObject, "content") + "°C");
                            break;
                        case 1:
                            bean.setType("血压"); bean.setType1("mmhg");
                            String[] dataTemp = getJSONValue(jsonObject, "content").split(",");//
                            bean.setContent("舒张压:" + dataTemp[0]+"mmhg\n"+"收缩压:" + dataTemp[1]+"mmhg");
                            break;
                        case 2:
                            bean.setType("血糖"); bean.setType1("mmol/l");bean.setType(getJSONValue(jsonObject, "content") + "°C");
                            String[] data1Temp = getJSONValue(jsonObject, "content").split(",");//
                            bean.setContent("餐前:" + data1Temp[0] + "mmol/l\n" + "餐后:" + data1Temp[1]+"mmol/l");
                            break;
                        case 3:
                            bean.setType("脉搏"); bean.setType1("次/分");
                            bean.setContent(getJSONValue(jsonObject, "content") + "次/分");
                            break;
                        case 4:
                            bean.setType("呼吸"); bean.setType1("次/分");
                            bean.setContent(getJSONValue(jsonObject, "content") + "次/分");
                            break;
                        case 5:
                            bean.setType("血氧"); bean.setType1("vol/dl");
                            bean.setContent(getJSONValue(jsonObject, "content") + "vol/dl");
                            break;
                        case 6:
                            bean.setType("尿量"); bean.setType1("ML");
                            bean.setContent(getJSONValue(jsonObject, "content") + "ML");
                            break;
                        case 7:
                            bean.setType("大便"); bean.setType1("次/日");
                            bean.setContent(getJSONValue(jsonObject, "content") + "次/日");
                            break;
                    }

                    if(i==length-1){
                        lid = getJSONINTValue(jsonObject, "id");
                    }
                    list.add(bean);
                }
                adapter.notifyDataSetChanged();
            }catch (Exception e){
                Log.d("zzzzz",e.toString());
            }
        }
    }

    private void initAdapter(){
//        for (int i=0;i<20;i++){
//            FeatureActivityBean bean=new FeatureActivityBean();
//            bean.setPatientInfo("王小二，女，68岁");
//            bean.setDoctor("黄华佗");
//            bean.setMeasureTime("2016-3-15 12:13:12");
//            bean.setType("体温");
//            bean.setType1("°C");
//            list.add(bean);
//        }
        adapter=new RecyclerViewCommonAdapter(activity,list) {
            @Override
            protected int getLayoutId() {
                return R.layout.feature_data_item_layout;
            }

            @Override
            protected void bindView(CommonViewHolder holder, final int position) {
                LinearLayout firstFather;
                TextView patient,type,type1,doctor,measureTime,temperature,data;
                firstFather=holder.getLinearLayout(R.id.firstFather);

                data = holder.getTextView(R.id.data);
                patient=holder.getTextView(R.id.info);
                type=holder.getTextView(R.id.type);
                type1=holder.getTextView(R.id.type1);
                doctor=holder.getTextView(R.id.doc);
                measureTime=holder.getTextView(R.id.time);
                temperature=holder.getTextView(R.id.data);

                data.setText(list.get(position).getContent());
                patient.setText(list.get(position).getPatientInfo());
                type.setText(list.get(position).getType());
                type1.setText(list.get(position).getType1());
                doctor.setText(list.get(position).getDoctor());
                measureTime.setText(list.get(position).getMeasureTime());
//                firstFather.setBackgroundResource(colors[position % 2]);
                holder.getRelativeLayout(R.id.bean_father).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onItemClickListener.onItemClick(null, position);
                    }
                });
            }
        };
        adapter.setOnItemClickListener(new RecyclerViewCommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                startOtherActivity(activity, DataPicActivity.class);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }


}
